/**
 * Created with IntelliJ IDEA.
 * Description:
 * User:
 * Date: 2024-09-28
 * Time: 14:47
 */
public class Sort {

    //直接插入排序
    public static void insertSort(int[] arr){
        for (int i = 1; i < arr.length; i++) {
            int tmp = arr[i];
            int j = i-1;
            for (; j >= 0; j--) {
                if(arr[j] > tmp){
                    arr[j+1] = arr[j];
                }else{
                    arr[j+1] = tmp;
                    break;
                }
            }
            //确保j位置的数，也就是前一个数能换位成功
            arr[j+1] = tmp;
        }
    }

    public static void shellSort(int[] arr){
        int gap = arr.length;
        while(gap > 1){
            gap /= 2;
            shell(arr, gap);
        }
    }

    private static void shell(int[] arr, int gap) {
        for (int i = gap; i < arr.length; i++) {
            int tmp = arr[i];
            int j = i-gap;
            for (; j >= 0; j -= gap) {
                if(arr[j] > tmp){
                    arr[j+gap] = arr[j];
                }else{
                    arr[j+gap] = tmp;
                    break;
                }
            }
            //确保j位置的数，也就是前一个数能换位成功
            arr[j+gap] = tmp;
        }
    }

    public static void selectSort(int[] arr){
        for (int i = 0; i < arr.length; i++) {
            int minIndex = i;
            for (int j = i+1; j < arr.length; j++) {
                if(arr[j] < arr[minIndex]){
                    minIndex = j;
                }
            }
            swap(arr, i, minIndex);
        }
    }

    private static void swap(int[] arr, int i, int minIndex) {
        int tmp = arr[i];
        arr[i] = arr[minIndex];
        arr[minIndex] = tmp;
    }

    public static void selectSort1(int[] arr) {
        int left = 0;
        int right = arr.length - 1;
        while (left < right) {
            int minIndex = left;
            int maxIndex = left;
            for (int i = left + 1; i <= right; i++) {
                if (arr[i] < arr[minIndex]) {
                    minIndex = i;
                }
                if (arr[i] > arr[maxIndex]) {
                        maxIndex = i;
                }
            }
            swap(arr,left,minIndex);
            if(maxIndex == 0){
                maxIndex = minIndex;
            }
            swap(arr,right,maxIndex);
            left++;
            right--;
        }
    }
}
